package com.study.web;

import cn.hutool.core.thread.ThreadUtil;
import com.study.dto.Student;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuzi
 * 2024/11/29 20:29
 */
@Slf4j
public class WebClientDemoA {
    WebClient webClient = WebClient.create();

    @Test
    public void getDemo() {
        WebClient webClient = WebClient.create("https://api.example.com");
        String result = webClient.get().uri("/data").retrieve()//retrieve() 方法用于获取响应体
                .bodyToMono(String.class)//retrieve() 方法用于获取响应体
                .block(); // 阻塞方法，等待响应System.out.println("Result: " + result);
        System.out.println(result);
    }

    @Test
    public void getDemoa() {
        webClient.get().uri("/unstable-endpoint").retrieve().bodyToMono(String.class).timeout(Duration.ofSeconds(3)) // 设置超时时间为 3 秒
                .retry(3) // 最多重试 3 次
                .onErrorReturn("Fallback response"); // 如果仍然失败则返回默认值
    }

    /**
     * 请求重试｜
     */
    @Test
    public void postJson() {
        Student student = new Student();
        Mono<String> response = webClient.post().uri("http://127.0.0.1:80/api/sync/postjson").contentType(MediaType.APPLICATION_JSON)//
                .bodyValue(student)//
                .retrieve().bodyToMono(String.class)//
                .timeout(Duration.ofSeconds(3)).retry(1);//重试3次
        response.subscribe(result -> System.out.println("响应结果: " + result), e -> {
            log.error("发送请求异常", e);
        });
        ThreadUtil.sleep(5, TimeUnit.SECONDS);
    }

    /**
     * 获取请求响应和响应头
     */
    @Test
    public void postJsonHeader() {
        Student student = new Student();
        Mono<ResponseEntity<String>> responseEntity = webClient.post()//
                .uri("http://127.0.0.1:80/api/sync/postjson")//
                .contentType(MediaType.APPLICATION_JSON)//
                .bodyValue(student) // 假设student是你的请求体对象
                .retrieve() // 获取ClientResponse
                .toEntity(String.class); // 获取包含响应头和响应体的Entity对象

        responseEntity.subscribe(entity -> {
            HttpHeaders headers = entity.getHeaders();
            HttpStatus statusCode = entity.getStatusCode();
            System.out.println("响应状态码");
            System.out.println(statusCode);
            String body = entity.getBody();
            System.out.println("响应头: " + headers);
            System.out.println("响应体: " + body);
        }, e -> {
            System.out.println("请求失败");
            System.out.println(e.getClass());
            e.printStackTrace();
        });
        ThreadUtil.sleep(5, TimeUnit.SECONDS);
    }
}
